package com.qf.qfdrivermqtt.service;

import com.qf.common.bean.R;
import com.qf.common.dto.DriverMqttDto;
import com.qf.common.feigns.DeviceApi;
import com.qf.common.feigns.DeviceTopicApi;
import com.qf.common.feigns.ProductApi;
import com.qf.common.model.QfDevice;
import com.qf.common.model.QfProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class AuthService {

    @Autowired
    private ProductApi productApi;

    @Autowired
    private DeviceApi deviceApi;

    @Autowired
    private DeviceTopicApi deviceTopicApi;

    @Autowired
    private MessageProducer messageProducer;

    public R auth(DriverMqttDto mqttDto) {

        String productKey = mqttDto.getProductKey();
        String deviceKey = mqttDto.getDeviceKey();
        String deviceSecret = mqttDto.getDeviceSecret();

        if (StringUtils.isEmpty(productKey) || StringUtils.isEmpty(deviceKey) || StringUtils.isEmpty(deviceSecret)){
            return R.fail(R.Code.FAILURE,"非法授权访问");
        }

        //根据productKey查询product
        QfProduct product = productApi.findByProductKey(productKey);
        if (product == null){
            return R.fail(R.Code.FAILURE,"productKey非法");
        }

        //根据deviceKey查询device
        QfDevice device = deviceApi.findByDeviceKey(deviceKey);
        if (device == null){
            return R.fail(R.Code.FAILURE,"deviceKey非法");
        }

        if (!device.getDeviceSecret().equals(deviceSecret)){
            return R.fail(R.Code.FAILURE,"deviceSecret非法");
        }

        //保障当前的mqtt服务器是正常在监控该设备的上报数据主题的
        subcribtDeviceTopic(deviceKey);

        //向设备返回登录需要的信息
        mqttDto.setUrl("tcp://10.31.160.2:1883");
        mqttDto.setIp("10.31.160.2");
        mqttDto.setPort(1883);
        mqttDto.setUsername("qf");
        mqttDto.setPassword("qf");
        mqttDto.setTenantId(device.getTenantId());

        return R.ok(mqttDto);
    }

    /**
     * 对于新创建的设备，保障mqtt服务器是正常监控的
     * @param deviceKey
     */
    private void subcribtDeviceTopic(String deviceKey) {
        List<String> dataTopics =  deviceTopicApi.findTopicByDeviceKey(deviceKey);

        dataTopics.forEach(topic->{
            ((MqttPahoMessageDrivenChannelAdapter) messageProducer).addTopic(topic);
        });

    }
}
